import { MockMethod } from 'vite-plugin-mock';
import Mock from 'mockjs';

// --- 工具函数和预置数据 ---

// 创建一个大的事件列表数据库，用于模拟分页 + 分类
const eventTypes = ['故障', '割接', '投诉', '重要活动', '日常'];
// const nodeflowsJson = JSON.stringify({
//   nodes: [
//     { id: "node-0", label: "事件生成", status: "success", name: "通用数字员工", icon: "#108ee9" },
//     { id: "node-1", label: "业务影响判断", status: "success", name: "通用数字员工", icon: "#108ee9" },
//     { id: "node-2", label: "故障定级", status: "success", name: "通用数字员工", icon: "#108ee9" },
//     { id: "node-3", label: "关注信息发布", status: "success", name: "张三1", icon: "#108ee9" },
//     { id: "node-4", label: "故障定界", status: "success", name: "通用数字员工", icon: "#108ee9" },
//     { id: "node-5", label: "故障定位", status: "success", name: "通用数字员工", icon: "#108ee9" },
//     { id: "node-6", label: "自动派单/督办", status: "success", name: "通用数字员工", icon: "#108ee9" },
//     { id: "node-7", label: "闭环信息发布", status: "error", name: "李四", icon: "#9A23FF" },
//     { id: "node-8", label: "事件闭环", status: "wait", name: "通用数字员工", icon: "#108ee9" }
//   ],
//   edges: [
//     { source: "node-0", target: "node-1" },
//     { source: "node-1", target: "node-2" },
//     { source: "node-2", target: "node-3" },
//     { source: "node-3", target: "node-4" },
//     { source: "node-4", target: "node-5" },
//     { source: "node-5", target: "node-6" },
//     { source: "node-6", target: "node-7" },
//     { source: "node-7", target: "node-8" }
//   ]
// });
const nodeflowsJson = JSON.stringify({
  nodes: [
    {
      id: "node-0", label: "事件生成", status: "success", name: "通用数字员工",
      icon: "{\"workflow\":0,\"position\":0,\"level\":2}"
    },
    {
      id: "node-1", label: "业务影响判断", status: "success", name: "通用数字员工",
      icon: "{\"workflow\":1,\"position\":1,\"level\":1}"
    },
    {
      id: "node-2", label: "故障定级", status: "success", name: "通用数字员工",
      icon: "{\"workflow\":3,\"position\":2,\"level\":1}"
    },
    {
      id: "node-3", label: "关注信息发布", status: "success", name: "张三1",
      icon: "{\"workflow\":1,\"position\":1,\"level\":0}"
    },
    {
      id: "node-4", label: "故障定界", status: "success", name: "通用数字员工",
      icon: "{\"workflow\":2,\"position\":1,\"level\":1}"
    },
    {
      id: "node-5", label: "故障定位", status: "success", name: "通用数字员工",
      icon: "{\"workflow\":1,\"position\":3,\"level\":1}"
    },
    {
      id: "node-6", label: "自动派单/督办", status: "success", name: "通用数字员工",
      icon: "{\"workflow\":1,\"position\":1,\"level\":1}"
    },
    {
      id: "node-7", label: "闭环信息发布", status: "error", name: "李四",
      icon: "{\"workflow\":1,\"position\":1,\"level\":2}"
    },
    {
      id: "node-8", label: "事件闭环", status: "wait", name: "通用数字员工",
      icon: "{\"workflow\":1,\"position\":1,\"level\":1}"
    }
  ],
  edges: [
    { source: "node-0", target: "node-3" },
    { source: "node-3", target: "node-6" },
    { source: "node-6", target: "node-8" },

    { source: "node-1", target: "node-4" },
    { source: "node-4", target: "node-7" },

    { source: "node-2", target: "node-5" },
    { source: "node-5", target: "node-7" },
    { source: "node-7", target: "node-8" }
  ]
});



const eventListDatabase = Mock.mock({
  'list|200': [{
    'event_id|+1': 1000,
    'id|+1': 1000,
    title: '@csentence(5, 15)',
    event_time: '@datetime("yyyy-MM-dd HH:mm:ss")',
    event_type: () => Mock.Random.pick(eventTypes),
    status: () => Mock.Random.pick(['待处理', '处理中', '已完成', '已关闭']),
    level: () => Mock.Random.pick(['紧急', '重要', '一般']),
    owner: '@cname',
    specialty: () => Mock.Random.pick(['核心网', '无线网', '传输网', 'IP网']),
    content: '@cparagraph(1, 3)',
    previous_step: '告警监控',
    current_step: '事件派发',
    deadline: '@datetime("yyyy-MM-dd HH:mm:ss")',
    nodeflows: nodeflowsJson,
  }]
}).list;


// 事件列表的表头字段
const eventListFields = [
  { title: '事件主题', istitle: 1 },
  { event_time: '发生时间', istitle: 1 },
  { event_type: '事件类型', istitle: 1 },
  { status: '事件状态', istitle: 1 },
  { owner: '责任人', istitle: 1 },
  { current_step: '当前处理环节', istitle: 1 },

  // 以下仅用于详情页
  { level: '紧急程度', istitle: 0 },
  { level: '当前处理环节内容及结果', istitle: 0 },
  { specialty: '专业领域', istitle: 0 },
  { content: '内容描述', istitle: 0 },
  { previous_step: '前一环节', istitle: 0 },
  { deadline: '截止时间', istitle: 0 },
];



// --- Mock 接口定义 ---

export default [
  // 1. 获取仪表盘总览数据
  {
    url: '/index/data', // 注意：请确保你的请求路径与这里一致
    method: 'get',
    response: (): RootResponse => { // 使用你定义的接口类型
      return {
        code: 1,
        message: '成功',
        data: {
          todayEvent: { value: Mock.Random.integer(10, 50), url: null },
          incompleteEvent: { value: Mock.Random.integer(5, 20), url: null },
          pendingManualActionEvent: { value: Mock.Random.integer(0, 10), url: null },
          incompleteOrder: { value: Mock.Random.integer(10, 30), url: null },
          timeOutOrder: { value: Mock.Random.integer(0, 5), url: null },
          dispatchFaultOrder: { value: Mock.Random.integer(20, 60), url: null },
          todayCut: { value: Mock.Random.integer(5, 15), url: null },
          incompleteCut: { value: Mock.Random.integer(2, 8), url: null },
          incompleteComplaintOrder: { value: Mock.Random.integer(3, 10), url: null },
          timeOutComplaintOrder: { value: Mock.Random.integer(0, 4), url: null },
          dispatchComplaintOrder: { value: Mock.Random.integer(5, 15), url: null },
          dailyRoutine: { value: Mock.Random.integer(80, 120), url: null },
          importantEvent: { value: Mock.Random.integer(1, 3), url: null },
          holidayEvent: { value: Mock.Random.integer(0, 2), url: null },
          publicOpinion: { value: Mock.Random.integer(0, 10), url: 'http://example.com/public-opinion' },
          networkSituaiton: { value: null, url: 'http://example.com/network-situation' },
          eventOverview: { value: null, url: 'http://example.com/event-overview' },
          workSchedule: { value: null, url: 'http://example.com/work-schedule' },
          scheduleRecord: { value: null, url: 'http://example.com/schedule-record' },
          jobPersonnel: {
            value: {
              dutyOfficer: [Mock.Random.cname()],
              majorCorePosition: [Mock.Random.cname(), Mock.Random.cname()],
              majorAccessPosition: [Mock.Random.cname(), Mock.Random.cname()],
            },
            url: null,
          },
          eventType: {
            value: ['故障', '割接', '投诉', '重要活动', '日常'],
            url: '/index/eventTypes',
          },
          employeeRunCount: { value: Mock.Random.integer(1000, 5000), url: null },
          onlineEmployee: { value: Mock.Random.integer(5, 20), url: null },
        },
      };
    },
  },

  // 2. 获取事件列表（模拟分页）
  {
    url: '/index/eventList',
    method: 'post',
    response: ({ body }: any) => {
      const { Page = 1, PageSize = 10, event_type } = body;

      // 先按类型筛选
      let filteredList = eventListDatabase;
      if (event_type) {
        filteredList = filteredList.filter((item) => item.event_type === event_type);
      }

      // 分页处理
      const total = filteredList.length;
      const start = (Page - 1) * PageSize;
      const end = Page * PageSize;
      const paginatedData = filteredList.slice(start, end);

      return {
        code: 1,
        message: '成功',
        data: {
          count: total,
          num_pages: Math.ceil(total / PageSize),
          current_page: Page,
          results: paginatedData,
        },
        fields: eventListFields,
      };
    }
  },



  // 3. 获取事件类型
  {
    url: '/index/eventTypes',
    method: 'get',
    response: (): eventTypesData => {
      return {
        code: 1,
        message: '成功',
        data: [
          { name: '故障', total: Mock.Random.integer(50, 100), active: Mock.Random.integer(5, 20) },
          { name: '割接', total: Mock.Random.integer(20, 50), active: Mock.Random.integer(2, 10) },
          { name: '投诉', total: Mock.Random.integer(30, 80), active: Mock.Random.integer(10, 25) },
          { name: '重要活动', total: Mock.Random.integer(5, 10), active: Mock.Random.integer(1, 3) },
          { name: '日常', total: Mock.Random.integer(5, 10), active: Mock.Random.integer(1, 3) },
          // { name: '保障', total: Mock.Random.integer(5, 10), active: Mock.Random.integer(1, 3) },
          // { name: '建议', total: Mock.Random.integer(5, 10), active: Mock.Random.integer(1, 3) },
          // { name: '管理', total: Mock.Random.integer(5, 10), active: Mock.Random.integer(1, 3) },
          // { name: '事件', total: Mock.Random.integer(5, 10), active: Mock.Random.integer(1, 3) },
        ]
      }
    }
  },

  // 4. 关闭事件
  {
    url: '/index/eventClose',
    method: 'post',
    response: ({ body }: any) => {
      console.log('关闭事件 ID:', body.id);
      return {
        code: 1,
        message: `成功关闭 ${body.id.length} 个事件`,
        data: {}
      }
    }
  },

  // 5. 删除事件
  {
    url: '/index/eventDel',
    method: 'post',
    response: ({ body }: any) => {
      console.log('删除事件 ID:', body.id);
      return {
        code: 1,
        message: `成功删除 ${body.id.length} 个事件`,
        data: {}
      }
    }
  },

  {
    url: "/index/DigitalEmployee/Choose",
    method: "get",
    response: () => ({
      code: 1,
      message: "获取成功",
      data: {
        "事件监控及调度": {
          position: [
            "事件生成数字员工", "业务影响判断数字员工", "故障定级数字员工", "信息发布数字员工",
            "故障定界数字员工", "故障定位数字员工", "自动派单/督办数字员工", "事件闭环数字员工"
          ],
          grade: ["初级", "中级", "高级"],
          status: ["在岗", "离岗", "未部署", "升级维护"],
          method: ["系统化能力", "自研工具"]
        },
        "网络割接管理": {
          position: [
            "事前检测数字员工", "异常监控数字员工", "运行观察管控数字员工", "割接质量分析数字员工"
          ],
          grade: ["初级", "中级", "高级"],
          status: ["在岗", "离岗", "未部署", "升级维护"],
          method: ["系统化能力", "自研工具"]
        },
        "突发事件及通信保障": {
          position: [
            "事件发现数字员工", "信息发布数字员工", "保障调度数字员工", "事件闭环数字员工"
          ],
          grade: ["初级", "中级", "高级"],
          status: ["在岗", "离岗", "未部署", "升级维护"],
          method: ["系统化能力", "自研工具"]
        },
        "投诉响应及处理": {
          position: [
            "投诉受理数字员工", "投诉定界数字员工", "工单转派数字员工",
            "处理进度督办数字员工", "投诉质检数字员工"
          ],
          grade: ["初级", "中级", "高级"],
          status: ["在岗", "离岗", "未部署", "升级维护"],
          method: ["系统化能力", "自研工具"]
        },
        "现场管理": {
          position: [
            "班组管理数字员工", "大值班上报数字员工", "大屏展示讲解数字员工", "监控现场质量评估数字员工"
          ],
          grade: ["初级", "中级", "高级"],
          status: ["在岗", "离岗", "未部署", "升级维护"],
          method: ["系统化能力", "自研工具"]
        },
        "质量分析": {
          position: [
            "监控日报数字员工", "例行分析数字员工", "周月数据分析数字员工"
          ],
          grade: ["初级", "中级", "高级"],
          status: ["在岗", "离岗", "未部署", "升级维护"],
          method: ["系统化能力", "自研工具"]
        }
      }
    })
  },

  // 数字员工新增修改
  {
    url: "/index/DigitalEmployee/set",
    method: "post",
    response: () => ({
      code: 1,
      message: "保存成功"
    })
  },

  // 数字员工搜索
  {
    url: "/index/DigitalEmployee/search",
    method: "post",
    response: (req) => {
      // 从请求体中获取分页参数
      const { Page = 1, PageSize = 10 } = req.body || {};

      const totalCount = 24;

      const getRandomInt = (min: number, max: number) =>
        Math.floor(Math.random() * (max - min + 1)) + min;

      const allData = Array.from({ length: totalCount }).map((_, i) => {
        const workflow = getRandomInt(0, 5);
        const position = getRandomInt(0, 4);
        const level = getRandomInt(0, 2);

        return {
          id: i + 1,
          name: `数字员工-${i + 1}`,
          icon: JSON.stringify({ workflow, position, level }),
          workflow: "网络割接管理",
          position: "运行观察管控数字员工",
          duty: "负责生成事件",
          level: "中级",
          description: "这是一个描述",
          run_status: "离岗",
          implement_method: "系统化能力",
          created_at: "2025-08-01 10:00:00",
        };
      });

      const numPages = Math.ceil(totalCount / PageSize);
      const start = (Page - 1) * PageSize;
      const end = Page * PageSize;
      const pagedData = allData.slice(start, end);

      return {
        code: 1,
        message: "查询成功",
        data: {
          count: totalCount,
          num_pages: numPages,
          current_page: Page,
          results: pagedData,
        },
      };
    },
  },


  // 类型列表
  {
    url: "/index/DigitalEmployee/type",
    method: "get",
    response: () => ({
      code: 1,
      message: "获取成功",
      data: [
        "事件监控及调度",
        "网络割接管理",
        "突发事件及通信保障",
        "投诉响应及处理",
        "现场管理",
        "质量分析"
      ]
    })
  },

  // 运行数据统计
  {
    url: "/index/DigitalEmployee/runData",
    method: "get",
    response: () => ({
      code: 1,
      message: "获取成功",
      data: {
        run_count: 1200,
        success_ratio: 95,
        time_savings: 480,
        performance_ratio: 90
      }
    })
  },

  // 离岗操作
  {
    url: "/index/DigitalEmployee/Left",
    method: "post",
    response: () => ({
      code: 1,
      message: "处理成功",
      data: {
        run_count: 1150,
        success_ratio: 93,
        time_savings: 450,
        performance_ratio: 88
      }
    })
  }

] as MockMethod[];

// 可选：将你的接口类型定义放在这个文件里或者单独文件
// 如果放在单独文件，请确保上面的 import 路径正确
interface RootResponse {
  code: number;
  message: string;
  data: any; // 使用 any 或具体的 Data 接口
}
interface eventTypesData {
  code: number;
  message: string;
  data: any[]; // 使用 any 或具体的 typesitem 接口
}